<template>
	<div class="container-fluid" :id="isFullScreen?'fullScreen':''">
    <div class="row">
        <b-alert class="topCenter" :variant="variant"
                 dismissible
                 fade
                 :show="showMsg">
          {{ msg }}
        </b-alert>
        <BlogCat :categories="categories" :curCat="category" :currentCatName="currentCatName"></BlogCat>

        <div class="col col-lg-3 articles" >
          <p class="add_article" v-if="currentCatName!='回收站'">
            <button class="btn btn-primary" @click="addArticle"><i class="fa fa-plus"></i> {{ currentCatName }} {{ currentId }}</button>            
          </p>
          

            
          <ul class="list-group list-group-flush" v-if="loadingArticle">
            <li class="list-group-item" v-for="(article,index) in articlesList.data" :key="article.id" @click="editArticle(index)"><router-link :to="{ name: 'article', params: { id: article.id }}" :class="article.status+(selectIndex==index?' hover':'')"><i class="c"></i> <span>{{ article.title }}</span>
                        <div>
                          <i class="fa fa-cog" aria-hidden="true"></i>
                          <span>
                            <ul class="_3FcHm">
                                <li class="_2po2r cRfUr" title="" v-if="article.status==='published'" @click="preview"><i class="fa fa-external-link _22XWG"></i>预览文章</li>
                              <template v-if="article.status!=='trashed'">                    
                                <li class="_2po2r cRfUr" title="" v-b-modal.mov-article><i class="fa fa-folder-open _22XWG"></i>移动文章</li>
                                <li class="_2po2r cRfUr" title="" v-b-modal.del-article><i class="fa fa-trash-o _22XWG"></i>删除文集</li>
                              </template>
                              <template v-if="article.status==='trashed'">
                                <li class="_2po2r cRfUr" title="" @click="restore"><i class="fa fa-share _22XWG"></i>恢复文章</li>
                              </template>
                            </ul>
                          </span>
                        </div>
            </router-link></li>
          </ul>

          <b-pagination v-if="loadingArticle && articlesList.total" size="md" @change="goPage" :total-rows="articlesList.total" v-model="current_page" :per-page="parseInt(articlesList.per_page)"></b-pagination>


          <b-modal id="mov-article" centered title="移动文章"  @ok="moveArticle" cancel-title="取消" ok-title="确定">
            <b-form-select class="mb-3" v-model="movCategory">
              <option v-for="cat in categories" :disabled="cat.id==category.id" :value="cat.id">{{ cat.name }}</option>
            </b-form-select>
          </b-modal>
          <b-modal id="del-article" centered title="删除文章"  @ok="delArticle" cancel-title="取消" ok-title="确定">
              确定要移动文章`<code>{{ title }}</code>`到回收站吗?
          </b-modal>
        </div>
        <div class="col col-lg-7">

            <b-form-input placeholder="请输入标题" v-model.trim="title" v-if="currentCatName!='回收站'"></b-form-input>
         
            <Editor @syncData="syncData" :input="input" @publishedAction="published" @saveAction="save" v-if="currentCatName!='回收站'"></Editor>
        		
          </div>
      </div>
	</div>
</template>

<style type="text/css">
.topCenter{position:fixed;width:320px;top:90px;z-index:1000;left:50%;margin-left:-160px;}
.container-fluid{background-color:#FFF;position:fixed;left:0;top:0;z-index:1000;}
.categories,.articles{padding-left:0;padding-right:0;}
.articles{position:relative;}
.articles ul.list-group{height:80%;}
.articles ul.pagination{position:absolute;bottom:0px;left:10px;}
.articles .list-group-item{padding:0;height:10%;max-height: 70px;}
.articles .list-group-item a{display:block;height:97%;width:100%;padding:10px;line-height: 40px;color:#333;border-left:3px solid #e6e6e6;background-color:#e6e6e6;position:relative;}
.articles .list-group-item a span{display:block;width:80%;overflow:hidden;-o-text-overflow: ellipsis;
    text-overflow: ellipsis;
    white-space: nowrap;}
.articles .list-group-item a.hover{ border-left-color: #ec7259;}
.articles .list-group-item a.published i.c{
    background: url(/img/sprite.9d24217.png) no-repeat -50px -25px;
        background-size: auto auto;
    background-size: 250px;float:left;margin:5px;height:30px;width:23px;
}

.list-group-item i{margin-right:4px;}
.articles .list-group-item a i.c{
    background: url(/img/sprite.9d24217.png) no-repeat -0px -25px;
        background-size: auto auto;
    background-size: 250px;float:left;margin:5px;height:30px;width:23px;
}

.articles  .list-group-item div{position:absolute;width:30px;height:30px;line-height:30px;text-align:center;display:none;right: 20px;
top: 15px;z-index:888;}
.articles  .list-group-item div span {
    display: block;
    margin-right: 20px;
    -o-text-overflow: ellipsis;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.articles .list-group-item a.hover div{
  display:block;
}
.articles  .list-group-item div:hover span ul{
  display:block;
}
.articles  .list-group-item div span ul{
  position:absolute;
  display:none;
  left: -60px;
  box-shadow: 0 5px 10px rgba(0,0,0,.2);
  top: 30px;
  z-index:1000;
  background-color:#FFF;
  border-radius:5px;
  color:#333;
  list-style:none;
  padding-left: 0px;
  padding-right:0px;
  padding-top: 3px;
  padding-bottom: 3px;
}
.articles  .list-group-item div span ul._3FcHm::before {
    border-left: 9px solid transparent;
    border-right: 9px solid transparent;
    border-bottom: 9px solid #fff;
    top: -9px;
    position: absolute;
    right: 12px;
    content: "";
    display: inline-block;
}
.articles  .list-group-item div span ul._3FcHm li{line-height:40px;height:40px;border-bottom:1px solid silver;padding:0 10px;cursor:pointer;}
.articles  .list-group-item div span ul._3FcHm li:last-child{border-bottom:none;}
.articles  .list-group-item div span ul._3FcHm li:hover{background-color:#333;color:#FFF;}

#fullScreen{width:100%;}
#fullScreen #editor {
    position: fixed;
    z-index: 1000;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
}
#fullScreen #editor textarea,#fullScreen #editor div{height:100%;}
#editor {
  margin: 0;
  height: 100%;
  font-family: 'Helvetica Neue', Arial, sans-serif;
  color: #333;
  background-color:#fcfaf2;
}
#editor #htmlMarkdown{overflow:scroll;max-height:100%;overflow-x: hidden;background-color:#fcfaf2;}
#editor #htmlMarkdown img{max-width:100%;}
.drop_box{border:1px dashed silver;height:45px;line-height:45px;text-align:center;}
#editor ul{height:45px;background-color:#EEE;margin-bottom:0;padding-left:15px;}
#editor ul li{list-style:none;float:left;line-height: 45px;font-size: 16px;margin-right:15px;}
#editor ul li:hover{background-color:#333;color:#FFF;}
#editor ul li.tGbI7{float:right;}
#editor ul li.cztJE{padding:0 10px;}
#editor ul li a {
    height: 45px;
    line-height: 45px;
    display: block;
    min-width: 45px;
    text-align: center;
}
#editor textarea, #editor div {
  display: inline-block;
  width: 49.7%;
  height: 100%;
  vertical-align: top;
  box-sizing: border-box;
  padding: 0 2px;
  height:90%;
}
#editor textarea {
  border: none;
  border-right: 1px solid #ccc;
  resize: none;
  outline: none;
  background-color: #f6f6f6;
  font-size: 14px;
  font-family: 'Monaco', courier, monospace;
  padding: 20px;
}
#editor code {
  color: #f66;
}
.add_article{font-size:18px;text-indent:10px;padding-top:20px;padding-bottom:10px;}
.add_article a{color:#333;} 
</style>
<script>	
var tmpheight=document.documentElement.clientHeight;
var newheight='height:'+(tmpheight-83)+'px';
var fullheight='height:'+(tmpheight-45)+'px';

import BlogCat from './blog-cat'
import Editor from './Editor'
import VueRouter from 'vue-router'
Vue.use(VueRouter);

const routes = [
  { path: '/article/:id',name:'article',component:resolve => require(['./WriterComponent.vue'], resolve)},
]

const router = new VueRouter({
  routes // short for `routes: routes`
})

var CancelToken = axios.CancelToken;
var source = CancelToken.source();

export default {
   router,
   data(){
		return {
      autoheight:newheight,
      loading:false,
      show:true,
      showMsg:false,
      loadingArticle:false,
      variant:'success',
      msg:'alert some message',
      article_id:null,
      current_page:1,
      old_page:1,
			input:'...',
      articlesList:null,
      selectIndex:0,
      currentArticle:null,
      oldCategory_id:null,
      category:null,
      movCategory:null,
      title:'',
      htmlContent:'',
      markdown:'',
      isFullScreen:false,
      categories:[],
		}
   },
   components: {
      BlogCat,Editor
    },
   computed: {
      currentId () {
        var currentId=this.$route.params.id;
        if(currentId&&!this.loading){
            source.cancel('Operation canceled by the user.');
            var that=this;
            axios.get('/rbac/blog/apiArticle',{
              params:{currentId:currentId}
            })
              .then(function (response) { 
                  var res=response.data;
                  that.current_page=res['page'];
                  that.categories=res['categories'];
                  that.currentArticle=res['currentArticle'];
                  that.title=res['currentArticle'].title;
                  that.input=res['currentArticle'].markdown;
                  that.article_id=res['currentArticle'].id;
                  if(res['hasCat']){
                      that.category=res['currentArticle'].category;
                  }else{
                      if(res['categories'].length>0){
                          that.category=res['categories'][0];                  
                      }
                  }

                  that.loading=true;
                  return currentId;
              })
              .catch(function(error) {
                 return currentId;
              });                  
        }else{
          return null;
        }
        
      },
      currentCatName:function(){
        var that=this;
        if(that.category!=null){
            var params={};
            var current_page=this.$route.params.current_page||this.current_page;
            var category_id=null;
            var catName=null;
            if(that.category.trash){
              category_id='trashed';
              catName='回收站';
              params={category_id:category_id,page:current_page,per_page:10};
              console.log('get tha articles of the trash');
            }else{
              category_id=that.category.id;
              catName=that.category.name;
              params={category_id:category_id,page:current_page,per_page:10};
              console.log('get tha articles of the category ',that.category.id);
            }
            if(category_id!=that.oldCategory_id){
                that.oldCategory_id=category_id;
            }else{
                console.log('the category not change...');
                return catName;
            }
            

            axios.get('/rbac/article/apiList',{params:params})
                 .then(function (response) {
                    that.articlesList=response.data;  
                    that.current_page=response.data.current_page;
                    that.loadingArticle=true;
                    var artList= response.data.data;
                    console.log('change the article selected ',that.article_id)
                    var find=false;
                    for (var i = artList.length - 1; i >= 0; i--) {
                        if(artList[i].id==that.article_id){
                          console.log('equal....')
                          that.selectIndex=i;
                          that.title=artList[i].title;
                          that.input=artList[i].markdown;
                          find=true;
                        }
                    }  
                    if(!find){
                      that.selectIndex=0;
                      if(artList.length>0){
                        that.title=artList[0].title;
                        that.input=artList[0].markdown;
                      }
                    }
                    // if(artList.data.length>0){
                    //   that.showPagination=true;   
                    // }          
                 })
                 .catch(function (error) {
                    console.log(error);
                 });
            return catName;
        }else{
          return null;
        }     
      }
   },   
   methods: {
     goPage:function(){
          var that=this;
          setTimeout(function(){
            if(that.current_page!=that.old_page){
              that.old_page=that.current_page;
            }else{
              console.log('the same page')
              return false;
            }
            console.log('go page...',that.current_page);
            var category_id=null;
            if(that.category.trash){
              category_id='trashed';
            }else{
              category_id=that.category.id;
            }
            var params={category_id:category_id,page:that.current_page,per_page:that.articlesList.per_page};
            axios.get('/rbac/article/apiList',{params:params})
                 .then(function (response) {
                    that.articlesList=response.data;  
                    var artList= response.data.data;
                    for (var i = artList.length - 1; i >= 0; i--) {
                        if(artList[i].id==that.currentId){
                          that.selectIndex=i;
                        }
                    }                            
                 })
                 .catch(function (error) {
                    console.log(error);
                 });
          },200);
      },
     alertMsg:function(msg,variant){
        this.msg=msg;
        this.variant=variant;
        this.showMsg=true;
        var that=this;
        setTimeout(function(){
          that.showMsg=false;
        },2000);
     },
     
     changeStatus:function(status){
        var that=this;
        var info='移动文章到回收站';
        if(status=='pending'){
          info='恢复文章';
        }
        axios.post('/rbac/article/apiMovArticle',{status:status,article_id:that.article_id})
        .then(function (response) { 
          if(response.data.msg=='success'){
            that.articlesList.data.splice(that.selectIndex,1); 
            that.alertMsg(info+'成功','success');
          }else{
            that.alertMsg(info+'失败','danger');
          }
        })
        .catch(function (error) {
          console.log(error);
        });
     },
     preview:function(){
        var that=this;
        setTimeout(function(){
          window.open('/?id='+that.article_id);
        },1000);
     },
     restore:function(){
        this.changeStatus('pending');
     },
     delArticle:function(){
        this.changeStatus('trashed');
     },
     moveArticle:function(e){
        console.log(this.movCategory,this.article_id,this.title);
        var that=this;
        axios.post('/rbac/article/apiMovArticle',{category_id:that.movCategory,article_id:that.article_id})
        .then(function (response) { 
          if(response.data.msg=='success'){
            that.articlesList.data.splice(that.selectIndex,1); 
            that.alertMsg('移动文章成功','success');
          }else{
            that.alertMsg('移动文章失败','danger');
          }
        })
        .catch(function (error) {
          console.log(error);
        });
     },
     addArticle:function(){
        this.selectIndex=null;
        this.article_id=null;
        this.input='';
        this.title='';
     },
     editArticle:function(index){
        this.selectIndex=index;
        var article=this.articlesList.data[index];
        this.currentArticle=article;
        this.article_id=article.id;
        this.input=article.markdown;
        this.title=article.title;
     },
     //Editor emit actions...
     syncData:function(data){
        console.log(data)
        if(data.markdown){
          this.markdown=data.markdown;
        }
        if(data.htmlContent){
          this.htmlContent=data.htmlContent;
        }
        if(_.has(data,'isFullScreen')){
          this.isFullScreen=data.isFullScreen;
        }
     },
     published:function(){
        this.articleStore('published');
     },
     save:function(){
        this.articleStore('pending');
     },

     articleStore:function(status){
        if(this.title==''){
          this.alertMsg('标题不能为空','danger');
          return false;
        }
        if(this.markdown==''){
          this.alertMsg('文章内容不能为空','danger');
          return false;
        }
        var that=this;
        axios.post('/rbac/article/apiStore',{article_id:that.article_id,category_id:that.category.id,status:status,title:that.title,markdown:that.markdown,html:that.htmlContent})
        .then(function (response) { 
          if(that.article_id!=null){
            that.articlesList.data[that.selectIndex]=response.data;
            if(status==='pending'){
               that.alertMsg('更新草稿成功','success');
            }else{
               that.alertMsg('更新文章成功','success');
            }
          }else{
            that.articlesList.data.push(response.data);
            if(status==='pending'){
               that.alertMsg('添加草稿成功','success');
            }else{
               that.alertMsg('添加文章成功','success');
            }
          }
          that.isFullScreen=false;
          that.title='';
          that.markdown='';
          that.article_id=null;

        })
        .catch(function (error) {
          console.log(error);
        });
     },
     initialData:function(){   
            var that=this;
            var currentId=this.$route.params.id;
            axios.get('/rbac/blog/apiArticle',{
              cancelToken: source.token,
              params:{currentId:currentId}
            })
              .then(function (response) { 
                  var res=response.data;
                  that.categories=res['categories'];
                  that.currentArticle=res['currentArticle'];
                  if(res['hasCat']){
                      that.category=res['currentArticle'].category;
                  }else{
                      if(res['categories'].length>0){
                          that.category=res['categories'][0];                  
                      }
                  }
              })
              .catch(function(thrown) {
                  if (axios.isCancel(thrown)) {
                    console.log('Request canceled', thrown.message);
                  } else {
                    // handle error
                  }
                });        
        
     },
    
     
   },

   mounted() { 
    this.initialData()   
    console.log('Component mounted.');
  },
}
</script>